package org.itworks.biodev.gui;

import java.awt.event.*;
import java.sql.*;
import java.util.*;
import java.util.Date;

import javax.swing.JOptionPane;

import org.itworks.biodev.model.*;
import org.itworks.helpers.mvc.*;

public class EditMeetingDialogControler extends AbstractControler {
	private EditMeetingDialogModel model;
	
	public EditMeetingDialogControler(EditMeetingDialogModel model, Meeting meeting) {
		this.model = model;
		this.model.setMeeting(meeting);
		
	}
	
	public EditMeetingDialogModel getModel() {
		return this.model;
	}
	

	@Override
	public void viewLoaded() {
		// TODO Auto-generated method stub
		try {
			this.getModel().setCustomersList( CustomerTable.getInstance().findAllOrderedByLastName());
			
			if(this.model.getMeeting() != null) {
				this.model.setIsUpdating(true);
				this.model.setInitMeeting(this.model.getMeeting());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void searchForCustomerButtonActionPerformed(ActionEvent actionEvent, String lastName) {
		// TODO Auto-generated method stub
		try {
			Vector<Customer> customers = CustomerTable.getInstance().findByLastNameLike(lastName.toUpperCase());
			this.model.setCustomersList(customers);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean okButtonActionPerformed(ActionEvent actionEvent, int i, Date date) {
		boolean retCode = false;
		if(i > -1) {
			if(date.after(new java.util.Date())) {
				

				// TODO Auto-generated method stub
				try {
					
					// R�cup�rer le client s�lectionn�
					Customer c = this.getModel().getCustomersList().elementAt(i);
					boolean add = false;
					if(this.model.getMeeting() == null) {
						add = true;
						this.model.setMeeting(new Meeting());
					}
					
					this.model.getMeeting().setHoster(c);
					this.model.getMeeting().setDateTime(new Timestamp(date.getTime()));
					
					if(add) {
						MeetingTable.getInstance().add(this.model.getMeeting());
					} else {
						MeetingTable.getInstance().update(this.model.getMeeting());
					}
					retCode = true;
				} catch(Exception e) {
					e.printStackTrace();
				}
			} else {
				JOptionPane.showMessageDialog(null,
					"La date sélectionnée est antérieure à la date actuelle.",
					"Erreur",
					JOptionPane.ERROR_MESSAGE);
			}
		} else {
			JOptionPane.showMessageDialog(null, "Aucun client n'a �t� s�lectionn� !", "Erreur", JOptionPane.ERROR_MESSAGE);
		}
		
		return retCode;
		
	}

	
	
}
